// src/utils/date.js
/**
 * 格式化时间
 * @param {Date|String|Number} date 时间
 * @param {String} fmt 格式
 */
export function parseTime(date, fmt = '{y}-{m}-{d} {h}:{i}:{s}') {
  if (typeof date === 'object') {
    if (!date.getTime) {
      date = new Date(date)
    }
  } else {
    if (typeof date === 'string') {
      date = date.replace(new RegExp(/-/gm), '/')
    }
    if (typeof date === 'number' && date.toString().length === 10) {
      date = new Date(date * 1000)
    }
    date = new Date(date)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = fmt.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // 注意：月份和日期需要补0
    if (key === 'm' || key === 'd') {
      value = value.toString().padStart(2, '0')
    } else if (key === 'h' || key === 'i' || key === 's') {
      value = value.toString().padStart(2, '0')
    }
    return value || 0
  })
  return time_str
}